<?php
namespace Home\Controller;

use Think\Cache\Driver\Redis;
use Think\Controller;
use AMQPConnection;
use AMQPExchange;
use AMQPChannel;

class IndexController extends Controller
{

	private $rabbitServer = ["host" => "127.0.0.1", "port" => 5672, "login" => "guest", "password" => "guest"];

	public function index(){
		echo "Welcome";
	}

	/**
	 * 用户请求
	 */
	public function init_request()
	{
		$conn = new AMQPConnection($this->rabbitServer);
		$connRes = $conn->connect();
		if (!$connRes) {
			die("Couldn't Connect to Server:" . $this->rabbitServer['host']);
		}
		$channel = new AMQPChannel($conn);
		$exchange = new AMQPExchange($channel);
		$exchange->setName("userRequest");
		for ($i = 100; $i < 300; $i++) {
			$arr = ["userid" => $i, "name" => "Name" . $i];
			$msg = json_encode($arr, JSON_UNESCAPED_UNICODE);
//			$redis = new Redis();
			$exchange->publish($msg, "userRequest");
		}
	}

	/**
	 * 初始化库存
	 */
	public function init_storage()
	{

		$rabbitServer = $this->rabbitServer;
		$conn = new AMQPConnection($rabbitServer);
		$connRes = $conn->connect();
		if (!$connRes) {
			die("Couldn't Connect to Server:" . $rabbitServer['host']);
		}
		$channel = new AMQPChannel($conn);
		$exchange = new AMQPExchange($channel);
		$exchange->setName("storage");
		for ($i = 1; $i <= 100; $i++) {
			$arr = ["id" => $i, "name" => "X1", "color" => "Red", ""];
			$msg = json_encode($arr, JSON_UNESCAPED_UNICODE);
			$exchange->publish($msg, "storage");
		}

	}

	public function getCount()
	{
		$server = $this->rabbitServer;
		$connection = new AMQPConnection($server);
		$m = $connection->connect();
		if (!$m) {
			die('Couldn\'t connection to the server');
		}
		$channel = new AMQPChannel($connection);
//        $exchange = new AMQPExchange($channel);
//        $exchange->setName("storage");
		$queue = new \AMQPQueue($channel);
		$queue->setName("storage");
		$queue->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); // 同上
		$count = $queue->declareQueue();
		dump($count);
	}

}